package com.jt.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jt.mapper.UserMapper;
import com.jt.pojo.User;
import com.jt.util.ObjectMapperUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import redis.clients.jedis.JedisCluster;

import java.util.UUID;

/**
 * @author Cx
 * @stage JT Of Fourth stage
 * @creat 2020-12-15 10:54
 */
@Service(timeout = 3000)
public class DubboUserServiceImpl implements DubboUserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private JedisCluster jedisCluster;

    @Override
    public void saveUser(User user) {
        byte[] bytes = user.getPassword().getBytes();
        String md5Pass = DigestUtils.md5DigestAsHex(bytes);
        user.setPassword(md5Pass).setEmail(user.getPhone());
        userMapper.insert(user);
    }

    @Override
    public String findUserByUP(User user) {
        // 校验用户名密码正确性 不存在返回null
        String md5Pass =
                DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
        user.setPassword(md5Pass);
        // 根据对象中不为null的属性作为where的条件
        QueryWrapper<User> queryWrapper = new QueryWrapper<>(user);
        User userDB = userMapper.selectOne(queryWrapper);
        // 判断对象是否有值
        if (userDB == null) {
            return null;
        }
        // 表示用户名密码正确 开启单点登录操作
        String ticket = UUID.randomUUID()
                .toString().replace("-", "");
        // 转化之前应该将数据脱敏 敏感数据应该剥离 不能暴露
        userDB.setPassword("48699684");
        String userJSON = ObjectMapperUtil.toJson(userDB);
        // 将数据存储到redis中
        jedisCluster.setex(ticket, 7 * 24 * 60 * 60, userJSON);
        return ticket;
    }

}
